#include "m0wig.h"
#include "ui_m0wig.h"
#include "qmqtt_message.h"
#include "brokenlinewig.h"
#include <QTimer>
#include <qmqtt_client.h>
#include <QByteArray>
#include <QFile>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QDebug>
#include <QMutex>
#include <QStandardPaths>
#include <QUuid>
M0Wig::M0Wig(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::M0Wig)
{


    ui->setupUi(this);
    //this->setStyleSheet("background-image: url(:/new/prefix1/pic/homepage.jpg); background-repeat: no-repeat; background-position: center;");
    this->setWindowFlags(Qt::FramelessWindowHint | windowFlags());
    this->setFixedSize(600,450);

}



void M0Wig::reJSON(QByteArray payload)
{
    //反序列化
    // 如果传入的 payload 为空，则从文件中读取
    if (payload.isEmpty()) {
        QFile file("gateway_app/json/up.json");

        // 验证文件是否存在
        if (!file.exists()) {
            qDebug() << "错误: 文件不存在 - " << file.fileName();
            return;
        }

        if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
            qDebug() << "错误: 无法打开文件 - " << file.errorString();
            return;
        }

        payload = file.readAll();
        file.close();

        // 验证读取的内容
        if (payload.isEmpty()) {
            qDebug() << "错误: 文件内容为空";
            return;
        }

        qDebug() << "读取的JSON内容:" << QString::fromUtf8(payload);

        // 输出前10个字符的详细信息
        qDebug() << "前10个字符的详细信息:";
        for (int i = 0; i < qMin(10, payload.size()); i++) {
            char c = payload[i];
            qDebug() << "位置" << i << ": 字符 = 0x" << QString::number((unsigned char)c, 16)
                     << ", 显示为 = " << (c >= 32 && c <= 126 ? QString(c) : QString("不可打印字符"));
        }

        // 移除UTF-8 BOM头
        if (payload.startsWith("\xEF\xBB\xBF")) {
            qDebug() << "检测到并移除了UTF-8 BOM头";
            payload = payload.mid(3); // 跳过前3个字节
        }
    }

    // 将 QByteArray 转换为 QJsonDocument
    QJsonParseError parseError;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(payload, &parseError);

    // 检查 JSON 数据是否有效
    if (jsonDoc.isNull()) {
        qDebug() << "JSON解析错误:" << parseError.errorString();
        qDebug() << "错误位置:" << parseError.offset;
        qDebug() << "错误附近的内容:" << QString::fromUtf8(payload.mid(qMax(0, parseError.offset-10), 20));
        return;
    }

    if (jsonDoc.isObject())
    {
        QJsonObject jsonObj = jsonDoc.object();

        // 解析顶层键值对
        type = jsonObj["type"].toInt();
        //判断type为4将开启历史上报
        if(type == 4)
        {
            qDebug() << "设置历史上报进程";
            result = jsonObj["result"].toInt();
            qDebug() << "Type:" << type;
            qDebug() << "Result:" << result;
            key = jsonObj["key"].toInt();
            qDebug() << "key:" << key;

            QList<QPair<qint64, QString>> historyData;
            QJsonArray dataArray = jsonObj["data"].toArray();

        }

        if(type == 4)
        {
            qDebug() << "设置历史上报进程";
            result = jsonObj["result"].toInt();
            qDebug() << "Type:" << type;
            qDebug() << "Result:" << result;
            key = jsonObj["key"].toInt();
            qDebug() << "key:" << key;

            QList<QPair<qint64, QString>> historyData;
            QJsonArray dataArray = jsonObj["data"].toArray();
            for (const auto& item : dataArray)
            {
                if (item.isObject())
                {
                    QJsonObject dataItem = item.toObject();
                    QJsonValue timeValue = dataItem["time"];
                    qint64 time = timeValue.toVariant().toLongLong();
                    QString val = dataItem["val"].toString();

                    historyData.append(qMakePair(time, val));

                    qDebug() << "Time:" << time;
                    qDebug() << "Value:" << val;
                }
            }
            qDebug() << "历史上报进程结束";
        }
        //emit historyDataReceived(key, historyData);

        else
        {
            result = jsonObj["result"].toInt();

            qDebug() << "Type:" << type;
            qDebug() << "Result:" << result;

            // 解析 data 数组
            QJsonArray dataArray = jsonObj["data"].toArray();
            for (const auto& item : dataArray) {
                if (item.isObject()) {
                    QJsonObject dataItem = item.toObject();
                    key = dataItem["key"].toInt();
                    val = dataItem["val"].toString();
                    if(key == 301)
                    {
                        ui->temEdit->setText(val);
                    }
                    else if(key == 302)
                    {
                        ui->humEdit->setText(val);
                    }
                    else if(key == 303)
                    {
                        ui->lightEdit->setText(val);
                    }
                    else if(key == 304)
                    {
                        ui->fireEdit->setText(val);
                    }

                    else if(key == 305)
                    {
                        if(val.contains("1"))
                        {
                            ui->lampEdit->setText("开");
                        }
                        else if(val.contains("0"))
                        {
                            ui->lampEdit->setText("关");
                        }
                    }
                    else if(key == 306)
                    {
                        if(val.contains("1"))
                        {
                            ui->fanEdit->setText("开");
                        }
                        else if(val.contains("0"))
                        {
                            ui->fanEdit->setText("关");
                        }
                    }


                    qDebug() << "Key:" << key;
                    qDebug() << "Value:" << val;
                }
            }
        }
    }
    else
    {
        qDebug() << "JSON格式错误: 不是有效的JSON对象";
        qDebug() << "原始数据:" << QString::fromUtf8(payload);
    }
}







M0Wig::~M0Wig()
{
    delete ui;

}

void M0Wig::dataUpSlot(QByteArray payload)
{
    //在这里处理接收到的数据
    QString data = QString::fromUtf8(payload);
    //ui->temEdit->setText(data);
    qDebug() << "接收到Up数据: " << data;
    //saveJSONToFile(payload, ":/new/prefix1/json/up.json");
    reJSON(payload);

}

void M0Wig::dataCtrlSlot(QByteArray payload)
{
    //在这里处理接收到的数据
    QString data = QString::fromUtf8(payload);
    ui->fanEdit->setText(data);
    qDebug() << "接收到Ctrl数据: " << data;
}


void M0Wig::on_lampBtnop_clicked()
{
    //电灯开
    QJsonObject dataObj;
    dataObj.insert("key",305);
    dataObj.insert("val","1");
    QJsonObject allObj;
    allObj.insert("data",dataObj);
    allObj.insert("type",2);
    // 序列化为JSON文档
    QJsonDocument doc(allObj);
    QByteArray data = doc.toJson(QJsonDocument::Compact);
    //QByteArray data = "fdaf";
    QMQTT::Message message;
    message.setTopic("/app/data/down");
    message.setPayload(data);
    qDebug() << data;
    GlobalVal::mqtt->publish(message);
}

void M0Wig::on_lampBtncl_clicked()
{
    //电灯关
    QJsonObject dataObj;
    dataObj.insert("key",305);
    dataObj.insert("val","0");
    QJsonObject allObj;
    allObj.insert("data",dataObj);
    allObj.insert("type",2);
    // 序列化为JSON文档
    QJsonDocument doc(allObj);
    QByteArray data = doc.toJson(QJsonDocument::Compact);

    QMQTT::Message message;
    message.setTopic("/app/data/down");
    message.setPayload(data);
    qDebug() << data;
    GlobalVal::mqtt->publish(message);
}
void M0Wig::on_fnaBtnop_clicked()
{
    //电扇开
    QJsonObject dataObj;
    dataObj.insert("key",306);
    dataObj.insert("val","1");
    QJsonObject allObj;
    allObj.insert("data",dataObj);
    allObj.insert("type",2);
    // 序列化为JSON文档
    QJsonDocument doc(allObj);
    QByteArray data = doc.toJson(QJsonDocument::Compact);

    QMQTT::Message message;
    message.setTopic("/app/data/down");
    message.setPayload(data);
    qDebug() << data;
    GlobalVal::mqtt->publish(message);
}
void M0Wig::on_fanBtncl_clicked()
{
    //电扇关
    QJsonObject dataObj;
    dataObj.insert("key",306);
    dataObj.insert("val","0");
    QJsonObject allObj;
    allObj.insert("data",dataObj);
    allObj.insert("type",2);
    // 序列化为JSON文档
    QJsonDocument doc(allObj);
    QByteArray data = doc.toJson(QJsonDocument::Compact);

    QMQTT::Message message;
    message.setTopic("/app/data/down");
    message.setPayload(data);
    qDebug() << data;
    GlobalVal::mqtt->publish(message);
}

void M0Wig::on_pushButton_clicked()
{
    //刷新上报
    // 设置 "keys" 字段
    QJsonArray keysArray;
    keysArray << 301 << 302 << 303 << 304 << 305 << 306 << 101 << 102;
    //设置总字段
    QJsonObject allObj;
    allObj.insert("type",1);
    allObj.insert("limit","all");
    allObj.insert("keys",keysArray);


    // 序列化为JSON文档
    QJsonDocument doc(allObj);
    QByteArray data = doc.toJson(QJsonDocument::Compact);

    QMQTT::Message message;
    message.setTopic("/app/data/down");
    message.setPayload(data);
    qDebug() << data;
    GlobalVal::mqtt->publish(message);
}
void M0Wig::on_pushButton_2_clicked()
{
    //温度折线图
    QString name = "温度";
    int key = 301;
    BrokenLineWig *tem = new BrokenLineWig();

    tem->setValue(name,key);
    tem->show();

}

void M0Wig::on_pushButton_3_clicked()
{
    //光照折线图
    QString name = "光照";
    int key = 303;
    BrokenLineWig *light = new BrokenLineWig();
    light->setValue(name,key);
    light->show();
}

void M0Wig::on_pushButton_4_clicked()
{

    //湿度折线图
    QString name = "湿度";
    int key = 302;
    BrokenLineWig *light = new BrokenLineWig();
    light->setValue(name,key);
    light->show();
}
